import React from "react";
import { message } from "antd";
import { observer, inject } from "mobx-react";

const HOCStoreInfo = (WrapComponent) => {
  @inject("setStoreInfo")
  @observer
  class NewComponent extends React.Component {
    state = {
      form: {},
      clogo: [], //电脑端logo
      pqr: [], //公众号二维码
      wechat_logo: [], //微信端logo
      options: [], //选择城市
      shopId: null, //商店ID
      isChange: [],
    };
    componentDidMount() {
      let {
        getSetStoreInfo,
        getSetProvence,
        getSetCities,
      } = this.props.setStoreInfo;

      //获取商店信息
      getSetStoreInfo().then((data) => {
        let obj = this.state;
        if (data.data.code === 200) {
          let allData = data.data.data[0];
          obj.clogo.push({
            thumbUrl: allData.clogo,
          });
          obj.pqr.push({ thumbUrl: allData.pqr });
          obj.wechat_logo.push({
            thumbUrl: allData.wechatLogo,
          });
          allData.storeArea = [];
          allData.storeArea.push(allData.locations.shopPro);
          allData.storeArea.push(allData.locations.shopCity);
          this.setFormValues(allData);
          //获取当前省份、城市id
          new Promise((resolve, reject) => {
            getSetProvence().then((data) => {
              let Provinces = data.data.data;
              resolve(Provinces);
            });
          })
            .then((data) => {
              return new Promise((resolve, reject) => {
                let province = data.filter(
                  (item) => item.provinceName === allData.locations.shopPro
                );
                resolve(province[0].provinceId);
              });
            })
            .then((id) => {
              return new Promise((resolve, reject) => {
                obj.isChange.push(id);
                getSetCities(id).then((data) => {
                  let Cities = data.data.data;
                  let city = Cities.filter(
                    (item) => item.cityName === allData.locations.shopCity
                  );
                //   console.log(city);
                  obj.isChange.push(city[0].cityId);
                  resolve();
                });
              });
            })
            .then(() => {
              obj.form = allData;
              this.setState(obj);
            });
        } else {
          message.error("请求商店信息数据失败");
        }
      });

      //获取省份信息
      getSetProvence().then((data) => {
        if (data.data.code === 200) {
          let provence = data.data.data;
          let obj = this.state;
          provence.forEach((element, index) => {
            let newObj = {
              label: element.provinceName,
              value: element.provinceId,
              index,
              isLeaf: false,
            };
            obj.options.push(newObj);
          });
          this.setState(obj);
        } else {
          message.error("请求省份信息数据失败");
        }
      });
    }
    setFormValues = (data) => {
      let { formOne, formTwo, formThree } = this.refs.form.refs;
      formOne.setFieldsValue(data);
      formTwo.setFieldsValue(data);
      formThree.setFieldsValue(data);
    };
    //上传图片之前
    beforeUploadImg = (file, attr) => {
      //进行验证
      const isJPG = file.type === "image/jpeg";
      const isJPEG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const size = file.size / 1024 / 1024;
      if (!(isJPG || isJPEG || isPNG)) {
        message.error("错误，图片格式应为jpg/jpge/png");
        return false;
      } else if (size >= 2) {
        message.warning("图片应<=2M");
        return false;
      } else {
        //验证成功后
        //制作图片缩略图
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          file.thumbUrl = e.target.result;
          let obj = this.state;
          obj[attr] = [];
          obj[attr].push(file);
          this.setState(obj);
        };
      }
      return false;
    };
    //移除图片
    handleRemove = (file, attr) => {
      let obj = this.state;
      obj[attr] = [];
      this.setState(obj);
    };
    //   表单字段值发生改变时变化
    onValuesChangeForm = (attr, changedValues, allValues) => {
      //   console.log(allValues);
      // let obj = this.state;
      // obj[attr] = allValues;
      // this.setState(obj);
    };
    //动态选择级联菜单
    loadData = (selectOptions) => {
      let id = selectOptions[0].value;
      let { getSetCities } = this.props.setStoreInfo;
      getSetCities(id).then((data) => {
        if (data.data.code === 200) {
          let cities = data.data.data;
          let newCity = [];
          cities.forEach((element) => {
            let newObj = {
              label: element.cityName,
              value: element.cityId,
            };
            newCity.push(newObj);
          });
          selectOptions[0].children = newCity;
          let obj = this.state;
          obj.options[selectOptions[0].index] = selectOptions[0];
          this.setState(obj);
        } else {
          message.error("请求城市信息失败");
        }
      });
    };
    //级联菜单选中值发生变化
    handleChangeCascader = (value, selectedOptions) => {
        let obj = this.state;
        obj.isChange = [];
        selectedOptions.forEach(element => {
            obj.isChange.push(element.label)
        });
        this.setState(obj);
    };
    //提交
    submit = async () => {
      let { getQuery, getPhotos } = this.props.setStoreInfo;
      let { formOne, formTwo, formThree } = this.refs.form.refs;
      let shopName = formOne.getFieldValue("shopName"); //商店名称
      let shopTity = formOne.getFieldValue("shopTity"); //商店标题
      let shopMs = formOne.getFieldValue("shopMs"); //商店描述
      let shopKw = formOne.getFieldValue("shopKw"); //商店关键字
      let shopPro = this.state.isChange[0];
      let shopCity = this.state.isChange[1];

      let shopAddress = formOne.getFieldValue("shopAddress"); //详细地址
      let ctime = formOne.getFieldValue("ctime"); //成团时间
      let rof = formOne.getFieldValue("rof"); //申请退款时间

      let lsType = formTwo.getFieldValue("lsType"); //客服类型
      let ls = formTwo.getFieldValue("ls"); //客服类型
      let ct = formTwo.getFieldValue("ct"); //客服电话
      let shopType = formTwo.getFieldValue("shopType"); //暂时关闭商店
      let shopCr = formTwo.getFieldValue("shopCr"); //关闭商店原因

      let clogo = this.state.clogo[0]; //电脑端logo 
      let pqr = this.state.pqr[0]; //公众号二维码
      let wechatLogo = this.state.wechat_logo[0]; //微信端logo

      let buyStatus = formThree.getFieldValue("formThree"); //关注后购买

      if (clogo.name) {
        clogo = await this.upLoadImg(clogo);
      } else {
        clogo = clogo.thumbUrl;
      }
      if (pqr.name) {
        pqr = await this.upLoadImg(pqr);
      } else {
        pqr = pqr.thumbUrl;
      }
      if (wechatLogo.name) {
        wechatLogo = await this.upLoadImg(wechatLogo);
      } else {
        wechatLogo = wechatLogo.thumbUrl;
      }
      let obj = {
        shopId: 1,
        shopName,
        shopTity,
        shopMs,
        shopKw,
        shopPro,
        shopCity,
        shopAddress,
        ctime,
        rof,
        lsType,
        ls,
        ct,
        shopType,
        shopCr,
        clogo,
        pqr,
        wechatLogo,
        buyStatus,
      };
      console.log(obj);
      getQuery(obj).then((data) => {
        if (data.data.code === 200) {
          message.success("更新数据成功");
        } else {
          message.error("更新数据失败");
        }
      });
    };

    upLoadImg = async (data) => {
      let { getPhotos } = this.props.setStoreInfo;
      let formData = new FormData();
      formData.append("file", data);
      let url = await getPhotos(formData).then((data) => {
        if (data.data.code === 200) {
          return data.data.data[0];
        } else {
          message.error("上传图片错误");
        }
      });
      return url;
    };

    render() {
      let methods = {
        beforeUploadImg: this.beforeUploadImg,
        handleRemove: this.handleRemove,
        submit: this.submit,
        onValuesChangeForm: this.onValuesChangeForm,
        loadData: this.loadData,
        handleChangeCascader: this.handleChangeCascader,
      };
      return (
        <WrapComponent
          {...this.state}
          {...methods}
          formRef={this.formRef}
          ref="form"
        ></WrapComponent>
      );
    }
  }
  return NewComponent;
};

export default HOCStoreInfo;
